package com.example.shgt;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.shgt.entity.LoginInfo;
import com.example.shgt.entity.RegisterInfo;
import com.example.shgt.entity.UserData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class LoginActivity extends AppCompatActivity {

    private EditText et_username;
    private EditText et_password;
    private CheckBox checkbox;
    private boolean is_login;
    private final Gson gson = new Gson();

    private SharedPreferences mSharedPreferences;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //初始化控件
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        checkbox = findViewById(R.id.checkbox);

        mSharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
//        mSharedPreferences = getSharedPreferences("user", MODE_PRIVATE);



        //是否勾选了记住密码
        is_login = mSharedPreferences.getBoolean("is_login", false);
        if (is_login) {
            String username = mSharedPreferences.getString("username", null);
            String password = mSharedPreferences.getString("password", null);
            et_username.setText(username);
            et_password.setText(password);
            checkbox.setChecked(true);
        }

        //点击注册
        findViewById(R.id.register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        //登录
        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = et_username.getText().toString();
                String password = et_password.getText().toString();

                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                    Toast.makeText(LoginActivity.this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
                } else {
                    // 发起网络请求进行登录
                    loginPost(username, password);


;
                }
            }
        });

        //checkBox的点击事件
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                is_login = isChecked;
            }
        });
    }

    private int loginPost(String username, String password) {
        new Thread(() -> {
            // url路径
            String url = "https://api-store.openguet.cn/api/member/tran/user/login";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", "479dbe79299a4653ada0432942111871")
                    .add("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                    .add("Content-Type", "application/json")
                    .build();

            // 请求体
            Map bodyMap = new HashMap<>();
            bodyMap.put("username", username);
            bodyMap.put("password", password);
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
            // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            } catch (NetworkOnMainThreadException ex) {
                ex.printStackTrace();
            }
        }).start();
        return 0;
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            Log.e("Network Error", "Request failed: " + e.getMessage());
            runOnUiThread(() -> Toast.makeText(LoginActivity.this, "请求失败： " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<LoginInfo>() {}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            LoginInfo dataResponseBody = gson.fromJson(body, jsonType);
            Log.d("info", dataResponseBody.toString());

            //如果登录成功，跳转到主界面
            if (dataResponseBody.getCode() == 200) { // 假设200表示成功
                runOnUiThread(() -> {
                    UserData userDataInfo = dataResponseBody.getData(); // 获取用户数据

                    UserData userData = new UserData();
                    userData.setAppKey(userDataInfo.getAppKey());
                    userData.setAvatar(userDataInfo.getAvatar());
                    userData.setId(userDataInfo.getId());
                    userData.setMoney(userDataInfo.getMoney());
                    userData.setUsername(et_username.getText().toString());

                    // 保存用户信息
                    saveUserData(userData);

                    // 检查是否勾选“记住密码”
                    if (is_login) {
                        // 保存用户名和密码
                        saveLoginInfo(et_username.getText().toString(), et_password.getText().toString());
                    } else {
                        // 清除保存的用户名和密码
                        clearLoginInfo();
                    }

                    // 登录成功后跳转到主界面
                    Toast.makeText(LoginActivity.this, "登入成功！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish(); // 结束当前活动
                });
            } else {
                runOnUiThread(() -> Toast.makeText(LoginActivity.this,"用户名或密码错误！", Toast.LENGTH_SHORT).show());
            }

        }
    };
    // 保存登录信息到 SharedPreferences
    private void saveLoginInfo(String username, String password) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putBoolean("is_login", true);
        editor.apply(); // 提交更改
    }

    // 清除保存的登录信息
    private void clearLoginInfo() {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.remove("username");
        editor.remove("password");
        editor.putBoolean("is_login", false);
        editor.apply(); // 提交更改
    }
    // 保存用户数据到 SharedPreferences
    private void saveUserData(UserData userData) {
        SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("appKey", userData.getAppKey());
        editor.putString("avatar", userData.getAvatar());
        editor.putString("userId", userData.getId());
        editor.putInt("money", userData.getMoney());
        editor.putString("username", userData.getUsername());
        editor.apply(); // 提交更改
    }
}

